package com.jingjin.humanityservice.util.ranking;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jingjin.humanityservice.util.ranking.cacheData.CacheDataInRedis;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

@Component
public class KrRankingHandler {

    private static final HttpClient httpClient = HttpClient.newHttpClient();

    @Resource
    private ObjectMapper objectMapper;

    @Resource
    private CacheDataInRedis cacheDataInRedis;

    public Map<String, Object> handleRoute(Map<String, String> queryParams, boolean noCache) throws Exception {
        String type = queryParams.getOrDefault("type", "hot");
        Map<String, Object> listResult = getList(type, noCache);

        Map<String, Object> routeData = new LinkedHashMap<>();
        routeData.put("name", "36kr");
        routeData.put("favicon", "https://www.36kr.com/favicon.ico");
        routeData.put("title", "36氪");
        Instant nowTime = Instant.now();
        // 将当前时间戳转换为上海时区
        ZonedDateTime Shanghai = nowTime.atZone(ZoneId.of("Asia/Shanghai"));
        routeData.put("nowTime", Shanghai);
        routeData.put("type", "热榜");
        routeData.put("link", "https://36kr.com/hot-list/catalog");
        routeData.put("total", ((List<?>) listResult.get("data")).size());

        List<Map<String, Object>> dataList = addIndexToDataList((List<Map<String, Object>>) listResult.get("data"));
        routeData.put("data", dataList);

        // 缓存数据到redis
        cacheDataInRedis.cacheData("36kr:hotSearch", routeData);

        return routeData;
    }

    private List<Map<String, Object>> addIndexToDataList(List<Map<String, Object>> dataList) {
        return IntStream.range(0, dataList.size())
                .mapToObj(index -> {
                    Map<String, Object> newItem = new LinkedHashMap<>();
                    newItem.put("index", index+1);
                    newItem.putAll(dataList.get(index));
                    return newItem;
                })
                .collect(Collectors.toList());
    }

    private Map<String, Object> getParams() {
        Map<String, String> typeOptions = Map.of(
                "hot", "人气榜",
                "video", "视频榜",
                "comment", "热议榜",
                "collect", "收藏榜"
        );

        Map<String, Object> params = new LinkedHashMap<>();
        params.put("type", Map.of("name", "热榜分类", "type", typeOptions));
        return params;
    }

    private Map<String, Object> getList(String type, boolean noCache) throws Exception {
        String url = "https://gateway.36kr.com/api/mis/nav/home/nav/rank/" + type;

        // 构建请求体
        Map<String, Object> requestBody = new LinkedHashMap<>();
        requestBody.put("partner_id", "wap");
        Map<String, Object> param = new LinkedHashMap<>();
        param.put("siteId", 1);
        param.put("platformId", 2);
        requestBody.put("param", param);
        requestBody.put("timestamp", Instant.now().toEpochMilli());

        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Content-Type", "application/json; charset=utf-8")
                .POST(HttpRequest.BodyPublishers.ofString(objectMapper.writeValueAsString(requestBody)))
                .build();

        HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());
        String body = response.body();

        // 打印响应体以供调试
//        System.out.println("API Response Body: " + body);

        JsonNode jsonNode = objectMapper.readTree(body);
        JsonNode dataNode = jsonNode.path("data");

        // 打印 dataNode 以供调试
//        System.out.println("Data Node: " + dataNode);

        Map<String, String> listType = Map.of(
                "hot", "hotRankList",
                "video", "videoList",
                "comment", "remarkList",
                "collect", "collectList"
        );

        String listKey = listType.getOrDefault(type, "hotRankList");
        JsonNode listNode = dataNode.path(listKey);

        // 打印 listNode 以供调试
//        System.out.println("List Node: " + listNode);

        if (listNode.isMissingNode() || listNode.isNull()) {
            throw new RuntimeException("The list data is missing or null. Check the API response structure.");
        }

        // 将 JsonNode 转换为 List<Map<String, Object>> 并处理
        List<Map<String, Object>> list = objectMapper.convertValue(listNode, new TypeReference<List<Map<String, Object>>>() {});

        if (list == null || list.isEmpty()) {
            throw new RuntimeException("The list data is empty or null after conversion. Check the response data format.");
        }

        List<Map<String, Object>> mappedList = list.stream().map(v -> {
            Map<String, Object> item = (Map<String, Object>) v.get("templateMaterial");
            if (item == null) {
                item = new LinkedHashMap<>();
            }
            Map<String, Object> resultItem = new LinkedHashMap<>();
            resultItem.put("title", item.getOrDefault("widgetTitle", ""));
            resultItem.put("url", "https://www.36kr.com/p/" + v.get("itemId"));
            resultItem.put("mobileUrl", "https://m.36kr.com/p/" + v.get("itemId"));

            return resultItem;
        }).collect(Collectors.toList());

        Map<String, Object> result = new LinkedHashMap<>();
        result.put("fromCache", false); // Placeholder, adjust if necessary
        result.put("updateTime", System.currentTimeMillis()); // Placeholder, adjust if necessary
        result.put("data", mappedList);

        return result;
    }


    public Map<String, Object> getRouteAndDataCombined(Map<String, String> queryParams, boolean noCache) throws Exception {
        return handleRoute(queryParams, noCache);
    }

    public Map<String, Object> getKrRanking() throws Exception {
        Map<String, String> queryParams = Map.of("type", "hot");
        return getRouteAndDataCombined(queryParams, false);
    }
}
